package com.gitee.wenbo0;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import static com.gitee.wenbo0.DictTextResultSetHandlerPlugin.CACHE_SQL;
import static com.gitee.wenbo0.DictTextResultSetHandlerPlugin.rsToList;

@Component
@Slf4j
public class ApplicationStartEventListener implements ApplicationListener<ApplicationStartedEvent> {
    @Resource
    DictTextResultSetHandlerPlugin dictTextResultSetHandlerPlugin;

    @Override
    public void onApplicationEvent(@NotNull ApplicationStartedEvent applicationStartedEvent) {
        HikariDataSource dataSource = (HikariDataSource) SpringContextHolder.getBean("dataSource");

        new Thread(() -> {
            while (true) {
                try (Connection conn = DriverManager.getConnection(dataSource.getJdbcUrl(), dataSource.getUsername(), dataSource.getPassword())) {
                    for (String tableName : dictTextResultSetHandlerPlugin.cacheTableNameList) {
                        List<Map<String, String>> cacheList = dictTextResultSetHandlerPlugin.timedCache.get(tableName, false);
                        if (cacheList == null) {
                            try (ResultSet rs = conn.prepareStatement(String.format(CACHE_SQL, tableName)).executeQuery()) {
                                List<Map<String, String>> list = rsToList(rs);
                                dictTextResultSetHandlerPlugin.timedCache.put(tableName, list);
                            }
                        }
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                log.debug("更新缓存数据成功");
                try {
                    Thread.sleep(1000 * 60);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

    }
}
